const childProcess = require("child_process"); // nodeJS 自带
const exec = childProcess.exec;

module.exports = {
  findPid,
  myexec,
  getCPU,
};
function myexec(cmd) {
  return new Promise((resolve, reject) => {
    exec(cmd, function (err, stdout, stderr) {
      if (err) {
        reject(err);
        return console.error(err);
      }
      resolve(stdout);
    });
  });
}
function findPid(name) {
  return new Promise((resolve, reject) => {
    // process 不用引入，nodeJS 自带
    // 带有命令行的list进程命令是：“cmd.exe /c wmic process list full”
    //  tasklist 是没有带命令行参数的。可以把这两个命令再cmd里面执行一下看一下效果
    // 注意：命令行获取的都带有换行符，获取之后需要更换换行符。可以执行配合这个使用 str.replace(/[\r\n]/g,""); 去除回车换行符
    let cmd = process.platform === "win32" ? "tasklist" : "ps aux";
    exec(cmd, function (err, stdout, stderr) {
      let pid = 0;
      if (err) {
        resolve(pid);
        return console.error(err);
      }
      stdout.split("\n").forEach((line) => {
        let processMessage = line.trim().split(/\s+/);
        // let processName = processMessage[0]; //processMessage[0]进程名称 ， processMessage[1]进程id
        //   if (processName === name) {
        //     return cb(processMessage[1])
        //   }
        if (processMessage.join("").includes(name)) {
          pid = parseInt(processMessage[1]);
        }
      });
      resolve(pid);
    });
  });
}
function getCPU() {
  return new Promise((resolve, reject) => {
    // process 不用引入，nodeJS 自带
    // 带有命令行的list进程命令是：“cmd.exe /c wmic process list full”
    //  tasklist 是没有带命令行参数的。可以把这两个命令再cmd里面执行一下看一下效果
    // 注意：命令行获取的都带有换行符，获取之后需要更换换行符。可以执行配合这个使用 str.replace(/[\r\n]/g,""); 去除回车换行符
    let cmd = process.platform === "win32" ? "tasklist" : "ps aux";
    exec(cmd, function (err, stdout, stderr) {
      let cpu = 0,
        memory = 0;
      if (err) {
        resolve({ cpu, memory });
        return console.error(err);
      }
      stdout.split("\n").forEach((line) => {
        let processMessage = line.trim().split(/\s+/);
        let cpu1 = processMessage[2];
        if (!cpu1 || isNaN(cpu1)) return;
        cpu1 = parseFloat(cpu1);
        cpu += cpu1;
        let memory1 = processMessage[3];
        if (!memory1 || isNaN(memory1)) return;
        memory1 = parseFloat(memory1);
        memory += memory1;
      });
      cpu = parseInt(cpu);
      memory = parseInt(memory);
      resolve({ cpu, memory });
    });
  });
}
